#include "stdafx.h"

#include "StickyTweetsXP.h"

#include "SwitchUserDialog.h"
#include "StickyTweetsAppXP.h"

CString switchScreenName;

INT_PTR CALLBACK SwitchUserDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	UNREFERENCED_PARAMETER(lParam);
	switch (message)
	{
	case WM_INITDIALOG:
		return (INT_PTR)SwitchUserDialog_Init(hDlg);

  case WM_CTLCOLORDLG:
    LOGBRUSH lb;
    static HBRUSH hBrush;

    lb.lbColor = RGB(154, 228, 232);
    lb.lbStyle = 0;

    hBrush = CreateBrushIndirect(&lb);
    return (INT_PTR)hBrush;

	case WM_COMMAND:
    if (HIWORD(wParam) == BN_CLICKED)
    {
		  switch (LOWORD(wParam))
      {
      case IDOK:
			  return (INT_PTR)cmdOk_Clicked(hDlg);

      case IDCANCEL:
        EndDialog(hDlg, StatusStSwitchUserCancel);
        return (INT_PTR)TRUE;
		  }
    }
		break;

  case WM_NOTIFY:
    switch (((LPNMHDR)lParam)->code)
    {
    case NM_DBLCLK:
      lvSwitchUser_Notify_DblClk(hDlg, (LPNMITEMACTIVATE)lParam);
      break;
    }
    break;
	}
	return (INT_PTR)FALSE;
}

BOOL SwitchUserDialog_Init(HWND hDlg)
{
  switchScreenName = L"";

  SendDlgItemMessage(hDlg, IDC_LV_SWITCHUSER, LVM_SETICONSPACING, 0, MAKELONG(96, 64));

  LVITEM lvItem;
  SecureZeroMemory(&lvItem, sizeof(LVITEM));
  lvItem.mask = LVIF_TEXT;

  lvItem.iItem = 0;
  lvItem.pszText = L"New User";
  SendDlgItemMessage(hDlg, IDC_LV_SWITCHUSER, LVM_INSERTITEM, 0, (LPARAM)&lvItem);

  CAtlList<CString> screenNames;
  StickyTweetsAppXP::GetInstance().GetScreenNames(screenNames);

  POSITION e = screenNames.GetHeadPosition();
  while (e) {
    CString& screenName = screenNames.GetNext(e);
    lvItem.iItem++;
    lvItem.pszText = const_cast<wchar_t*>(screenName.GetString());
    SendDlgItemMessage(hDlg, IDC_LV_SWITCHUSER, LVM_INSERTITEM, 0, (LPARAM)&lvItem);
  }

  return TRUE;
}

BOOL cmdOk_Clicked(HWND hDlg)
{
  StickyTweetsStatus status(StatusStOk);
  StickyTweetsAppXP& app = StickyTweetsAppXP::GetInstance();

  CString screenName;

  LRESULT index = SendDlgItemMessage(hDlg, IDC_LV_SWITCHUSER, LVM_GETSELECTIONMARK, 0, 0);
  if (index > 0)
  {
    TCHAR buffer[MaxLoadString];

    LVITEM item;
    SecureZeroMemory(&item, sizeof(LVITEM));
    item.mask = LVIF_TEXT;
    item.iItem = index;
    item.pszText = buffer;
    item.cchTextMax = MaxLoadString;
    SendDlgItemMessage(hDlg, IDC_LV_SWITCHUSER, LVM_GETITEM, 0, (LPARAM)&item);
    screenName = item.pszText;
  }

  if (index >= 0 && screenName != app.GetSettings().ScreenName)
  {
    if (status == StatusStOk)
    {
      switchScreenName = screenName;
      status = index == 0 ? StatusStSwitchUserNew : StatusStSwitchUser;
    }
  }
  else
  {
    status = StatusStSwitchUserCancel;
  }

  EndDialog(hDlg, status);
  return TRUE;
}

VOID lvSwitchUser_Notify_DblClk(HWND hDlg, LPNMITEMACTIVATE item)
{
  cmdOk_Clicked(hDlg);
}